package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述:93. 复原 IP 地址
 *
 * @author Madison You
 * @created 22:23
 */
public class Mid_93_RestoreIpAddresses {
    public static void main(String[] args) {
        new Mid_93_RestoreIpAddresses().restoreIpAddresses("25525511135");
    }

    List<String> list = new ArrayList<>();

    List<String> temp = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        back(s, 0);
        return list;
    }

    private void back(String s, int index) {
        if (s.length() == index && temp.size() == 4) {
            list.add(temp.stream().collect(Collectors.joining(".")));
            return;
        }
        for (int i = index; i < s.length(); i++) {
            String substring = s.substring(index, i + 1);
            if (check(substring)) {
                temp.add(substring);
            }else {
                continue;
            }
            back(s, i + 1);
            temp.remove(temp.size() - 1);
        }
    }

    private boolean check(String str) {
        if (str.length() > 1 && str.startsWith("0")) {
            return false;
        }
        if (str.length() > 3) {
            return false;
        }
        int num = Integer.parseInt(str);
        if (num >= 0 && num <= 255) {
            return true;
        }
        return false;
    }
}
